package br.com.devschool.util;

import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * @author ATILLA
 *
 */
public class BaseDAO {

	private Session 		session;
	private Transaction 	transaction;
	
	protected void openSession() {
		if(session == null || !session.isOpen()) {
			session = ConnectionFactory.getSessionfactory().openSession();
		}
	}
	
	protected void closeSession() {
		if(session.isOpen()){
			session.close();
		}
	}
	
	protected void beginTransaction() {
		transaction = session.beginTransaction();
	}
	
	protected void commit() {
		transaction.commit();
	}
	
	protected void rollback() {
		transaction.rollback();
	}
	
	protected Session getSession() {
		return session;
	}
	
	protected Transaction getTransaction() {
		return transaction;
	}

	protected void printModelToPersistObject(){
		System.out.println("\n<<=== Model To Persist Object ===>>\n");
		System.out.println("try {");
		System.out.println("    openSession();");
		System.out.println("    beginTransaction();");
		System.out.println("    getSession().save(object);");
		System.out.println("    commit();");
		System.out.println("    return true;");
		System.out.println("} catch (HibernateException e) {");
		System.out.println("    rollback();");
		System.out.println("    e.printStackTrace();");
		System.out.println("    throw new Exception(e);");
		System.out.println("} catch (Exception e) {");
		System.out.println("    rollback();");
		System.out.println("    e.printStackTrace();");
		System.out.println("    throw new Exception(e);");
		System.out.println("} finally {");
		System.out.println("    closeSession();");
		System.out.println("}");
		System.out.println("\n<<===============================>>\n");
	}
}